package com.star.spring.sharding.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.star.spring.sharding.entity.Order;
import com.star.spring.sharding.entity.OrderItem;
import com.star.spring.sharding.service.OrderItemService;
import com.star.spring.sharding.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderItemService orderItemService;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public String createOrder(@RequestParam Long userId,
                              @RequestParam Long addressId,
                              @RequestParam String productName,
                              @RequestParam BigDecimal price,
                              @RequestParam Integer quantity) {
        // 创建订单
        Order order = new Order(userId, addressId, "CREATED");
        orderService.save(order);

        // 创建订单项
        OrderItem orderItem = new OrderItem(order.getOrderId(), userId, productName, price, quantity);
        orderItemService.save(orderItem);

        return "订单创建成功，订单ID: " + order.getOrderId();
    }

    /**
     * 根据订单ID查询订单
     */
    @GetMapping("/{orderId}")
    public Order getOrderById(@PathVariable Long orderId) {
        return orderService.getById(orderId);
    }

    /**
     * 根据用户ID查询订单列表
     */
    @GetMapping("/user/{userId}")
    public List<Order> getOrdersByUserId(@PathVariable Long userId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return orderService.list(queryWrapper);
    }

    /**
     * 分页查询订单
     */
    @GetMapping("/page")
    public Page<Order> getOrderPage(@RequestParam(defaultValue = "1") Integer pageNo,
                                    @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Order> page = new Page<>(pageNo, pageSize);
        return orderService.page(page);
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/{orderId}")
    public String deleteOrder(@PathVariable Long orderId) {
        // 先删除订单项
        QueryWrapper<OrderItem> itemWrapper = new QueryWrapper<>();
        itemWrapper.eq("order_id", orderId);
        orderItemService.remove(itemWrapper);

        // 再删除订单
        orderService.removeById(orderId);

        return "订单删除成功";
    }
}